<template>
  <view>
    <view class="map">
      <map style="width: 100%; height: 750rpx;" :longitude="Number(longitude)" :latitude="Number(latitude)"
           :markers="markers">
        <cover-image class="somgImg" src="@/static/image/map/blueOpen.png" mode="" @click="somgSignIn"
                     v-if="tiringDetail.processState == 0"></cover-image>
        <cover-image class="somgImg" src="@/static/image/map/grayOpen.png" mode=""
                     v-if="tiringDetail.processState == 1"></cover-image>
        <cover-image class="somgImg" src="@/static/image/map/grayclone.png" mode=""
                     v-if="tiringDetail.processState == 2"></cover-image>
        <!--         <cover-image class="backIcon" src="@/static/image/back.png" mode="" @click="backUrl"></cover-image> -->
      </map>
    </view>
    <view class="pb30">

      <uni-card>
        <textarea v-model="parme.scoreContent" placeholder="故障描述：" class="describe" maxlength="100"
                  :disabled="types == 1"/>
      </uni-card>
      <view class="tipText" v-if="!(types == 1)">
        已输入
        <text>{{ parme.scoreContent.length }}</text>
        /100
      </view>
      <uni-card>
        <view class="" @touchmove.prevent.stop="">
          <view class="tipText textleft" v-show="!parme.repairSign">签字</view>
          <canvas class="canvasHimc mycanvasrepair" canvas-id="mycanvasrepair"
                  @touchstart="touchstart($event,'mycanvasrepair')" @touchmove="touchmove"
                  @touchend="touchend" v-show="!parme.repairSign"></canvas>
          <view class="" @click="clear('mycanvasrepair')" v-show="!parme.repairSign">清除</view>
          <image :src="parme.repairSign" mode="" class="canvasHimc" v-show="parme.repairSign"></image>
          <view class="f24" v-show="parme.repairSign">
            维修人 {{ tiringDetail.repairPeople }}
            {{
              tiringDetail.recordList.length > 2 ? tiringDetail.recordList[tiringDetail.recordList.length - 2].createTime : ''
            }}
          </view>
        </view>
      </uni-card>

      <uni-card v-if="types == 1">
        <view class="adminContent">
          <view class="flex1" @touchmove.prevent.stop="">
            <view class="tipText textleft" v-show="!parme.confirmSign">签字</view>
            <canvas class="canvasHimc mycanvasAdmin" canvas-id="mycanvasAdmin"
                    @touchstart="touchstart($event,'mycanvasAdmin')" @touchmove="touchmove"
                    @touchend="touchend" v-show="!parme.confirmSign"></canvas>
            <view class="" @click="clear('mycanvasAdmin')" v-show="!parme.confirmSign">清除</view>
            <image :src="parme.confirmSign" mode="" class="canvasHimc" v-show="parme.confirmSign"></image>

            <view class="f24" v-show="parme.confirmSign">
              确认人 {{ tiringDetail.confirmPeople }}
              {{
                tiringDetail.recordList.length > 2 ? tiringDetail.recordList[tiringDetail.recordList.length - 1].createTime : ''
              }}
            </view>
          </view>
          <view class="success" v-show="parme.confirmSign">
            <image src="@/static/image/polling/succIconB.png" mode="" class="sureIcon"></image>
            <text>通过</text>
          </view>
        </view>
      </uni-card>
      <!-- 提交人 签名信息 -->
      <view class="steps">
        <tm-timeline>
          <tm-timeline-item v-for="record in tiringDetail.recordList" color="green" :size="32" type="fill"
                            icon="tmicon-check" :time="record.createTime">
            <tm-sheet no-level :shadow="2" :round="3" :margin="[0, 10]">
              <tm-text
                  :label=record.remark
              ></tm-text>
            </tm-sheet>
          </tm-timeline-item>
        </tm-timeline>
      </view>
      <view class="submitd" @click="rescueComplet(1)" v-if="types == 0">维修完成</view>
      <view class="submitd" @click="surepass(2)" v-else-if="types == 1">确认通过</view>
    </view>


  </view>
</template>

<script>
import UniCard from "@/uni_modules/uni-card/components/uni-card/uni-card.vue";
import {getElevatorRepair, marchElevatorRepair, submitElevatorRepair} from "@/api/iot/elevatorRepair";
import {ossUpload} from "@/api/system/oss";
import {onPullDownRefresh} from "@dcloudio/uni-app";
import lo from "@/tmui/tool/dayjs/esm/locale/lo";

export default {
  components: {UniCard},
  data() {
    return {
      repairautograph: false,//维修签字
      Sureflag: false,//管理签字

      parme: {
        scoreContent: "",//故障描述
        repairSign: "",//维修人签字
        confirmSign: "",//确认人签字
      },
      repairId: "",//故障id
      tiringDetail: {
        recordList: [],
      },
      ctx: '', //绘图图像
      points: [],//路径点集合 
      longitude: "",
      latitude: "",
      types: "",//上个页面状态 更新用
      markers: [],
    }
  },
  // 画布
  onLoad(e) {
    this.repairId = e.repairId
    this.types = e.types

    this.getGride();
    let that = this;
    uni.getLocation({
      type: 'gcj02',
      success: function (da) {
        that.longitude = da.longitude
        that.latitude = da.latitude
      },
    });
  },
  methods: {
    async getGride() {
      const res = await getElevatorRepair(this.repairId);
      await uni.setNavigationBarTitle({
        title: res.elevatorName,
      })
      this.tiringDetail = res
      Object.keys(this.parme).forEach((key, value) => {
        this.parme[key] = res[key] ? res[key] : ''
      })
      if (this.tiringDetail.processState != 0) {
        this.markers = [{
          id: 300,
          latitude: Number(this.tiringDetail.latitudeStart),
          longitude: Number(this.tiringDetail.longitudeStart),
          iconPath: "/static/img/map/pitch1.png",
        }, {
          id: 301,
          latitude: Number(this.tiringDetail.latitudeEnd),
          longitude: Number(this.tiringDetail.longitudeEnd),
          iconPath: "/static/img/map/place1.png",
        }]
      }
    },
    // 签到
    async somgSignIn() {
      let that = this;
      await marchElevatorRepair({
        repairId: that.repairId,
        longitude: that.longitude,
        latitude: that.latitude
      });
      this.tiringDetail.processState = 1
      await this.getGride()
      await uni.showToast({
        title: '签到成功',
        icon: 'none',
      });
    }
    ,
    async rescueComplet() {
      let that = this;
      console.log(this.tiringDetail);
      if (this.tiringDetail.processState == 0) {
        uni.showToast({
          title: '请确认开始维修',
          icon: 'none',
        });
        return
      }
      if (!this.parme.scoreContent) {
        uni.showToast({
          title: '请输入故障描述',
          icon: 'none',
        });
        return
      } else if (!this.repairautograph) {
        uni.showToast({
          title: '请输入签名',
          icon: 'none',
        });
        return
      }

      uni.canvasToTempFilePath({
        canvasId: 'mycanvasrepair',
        success: async function (res) {
          const files = await ossUpload(res.tempFilePath);
          const defa = await submitElevatorRepair({
            type: 1,
            repairId: that.repairId,
            repairSign: files.url,
            scoreContent: that.parme.scoreContent,
          });
          console.log(defa)
          if (defa) {
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 2];
            //#ifdef APP-PLUS
            prevPage.$vm.getByStatus(that.types, true)
            // #endif
            //#ifdef H5
            prevPage.getByStatus(that.types, true)
            // #endif
            uni.navigateBack({})

          }
        }
      })
    },
    async surepass() {
      if (!this.Sureflag) {
        uni.showToast({
          title: '请填写确认人签字',
          icon: 'none',
        });
        return
      }
      let that = this;
      uni.canvasToTempFilePath({
        canvasId: 'mycanvasAdmin',
        success: async function (res) {
          const files = await ossUpload( res.tempFilePath)
          const dsf = await submitElevatorRepair({
            type: 2,
            repairId: that.repairId,
            confirmSign: files.url,
          })
          if (dsf) {
            var pages = getCurrentPages();
            var prevPage = pages[pages.length - 2];
            //#ifdef APP-PLUS
            prevPage.$vm.getByStatus(that.types, true)
            // #endif
            //#ifdef H5
            prevPage.getByStatus(that.types, true)
            // #endif
            uni.navigateBack({})
          }

        }
      })


    },


    //触摸开始，获取到起点
    touchstart: function (e, id) {
      this.ctx = uni.createCanvasContext(id, this);   //创建绘图对象
      if (id == 'mycanvasrepair') {
        this.repairautograph = true
      } else if (id == 'mycanvasAdmin') {
        this.Sureflag = true;
      }
      //设置画笔样式
      this.ctx.lineWidth = 4;
      this.ctx.lineCap = "round"
      this.ctx.lineJoin = "round"

      let startX = e.changedTouches[0].x;
      let startY = e.changedTouches[0].y;
      let startPoint = {X: startX, Y: startY};
      this.points.push(startPoint);
      //每次触摸开始，开启新的路径
      this.ctx.beginPath();
    },

    //触摸移动，获取到路径点
    touchmove: function (e) {
      e.preventDefault(); // 如果需要，阻止默认行为
      let moveX = e.changedTouches[0].x;
      let moveY = e.changedTouches[0].y;
      let movePoint = {X: moveX, Y: moveY};
      this.points.push(movePoint);       //存点
      let len = this.points.length;
      if (len >= 2) {
        this.draw();                   //绘制路径
      }

    },

    // 触摸结束，将未绘制的点清空防止对后续路径产生干扰
    touchend: function () {
      this.points = [];
    },

    /* ***********************************************
    #   绘制笔迹
    #	1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
    #	2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
    #	3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
    ************************************************ */
    draw: function () {
      let point1 = this.points[0]
      let point2 = this.points[1]
      this.points.shift()
      this.ctx.moveTo(point1.X, point1.Y)
      this.ctx.lineTo(point2.X, point2.Y)
      this.ctx.stroke()
      this.ctx.draw(true)
    },
    clear(id) {
      let that = this;
      uni.getSystemInfo({
        success: function (res) { // res - 各种参数
          let info = uni.createSelectorQuery().select(`.${id}`);
          info.boundingClientRect(function (data) { //data - 各种参数
            console.log(data)  // 获取元素宽度

            if (id == 'mycanvasrepair') {
              that.repairautograph = false
            } else if (id == 'mycanvasAdmin') {
              that.Sureflag = false;
            }
            //清除画布
            that.ctx.clearRect(0, 0, data.width, data.height)
            that.ctx.draw(true)
          }).exec()
        }
      });
    },
  },
}
</script>

<style scoped lang="scss">
.somgImg {
  width: 136rpx;
  height: 136rpx;
  position: absolute;
  bottom: 30rpx;
  left: 50%;
  transform: translateX(-50%);
}

.backIcon {
  width: 20px;
  height: 20px;
  position: fixed;
  top: 100rpx;
  left: 30rpx;
}

.describe {
  width: 100%;
  height: 226rpx;
  font-size: 24rpx;
}

.tipText {
  padding: 5px 43rpx;
  color: #989BA6;
  text-align: right;
  font-size: 24rpx;

  text {
    font-size: 30rpx;
    font-weight: bold;
  }
}

.textleft {
  text-align: left;
  padding: 0;
}

.canvasHimc {
  height: 260rpx;
  width: 100%;
}

.uni-card {
  width: 670rpx;
  /* height: 220rpx; */
  background: #FFFFFF;
  box-shadow: 0rpx 10rpx 10rpx 0rpx rgba(52, 54, 61, 0.05);
  border: none;
  border-radius: 16rpx;
  margin: 0 auto;
  margin-top: 20rpx;
}

/* 返回图标 */
.back {
  position: fixed;
  top: 119rpx;
  left: 40rpx;
}

/* 内容区域 */
.main {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  border-bottom: 1rpx solid #E2E6EF;
  padding-bottom: 15rpx;
}

.main image {
  width: 80rpx;
  height: 80rpx;
  background: #E2E6EF;
  border: 4rpx solid #F0F3F6;
  border-radius: 50%;
  margin-right: 18rpx;

}

.main-time {
  font-size: 24rpx;
  color: #34363D;
}

.main-time text {
  margin-left: 20rpx;
}

/* 头像下面内容 */
.content {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  margin-top: 20rpx;
  font-size: 30rpx;
  font-weight: 400;
  color: #34363D;
}

.alarm image {
  width: 24rpx;
  height: 24rpx;
  vertical-align: middle;
  margin-right: 10rpx;
}

.alarm text {
  font-size: 24rpx;
  color: #34363D;

}

.address {
  font-size: 24rpx;
  font-family: PingFang SC;
  font-weight: 400;
  color: #989BA6;
}

.submitd {
  width: 670rpx;
  height: 104rpx;
  background: #017EFE;
  box-shadow: 0px 10px 15px 0px rgba(1, 126, 254, 0.2);
  border-radius: 52px;
  text-align: center;
  color: #FFFFFF;
  line-height: 104rpx;
  margin: 0 auto;
  font-size: 36rpx;
  margin-top: 40rpx;
}

.adminContent {
  display: flex;
  align-items: center;

  .flex1 {
    flex: 1;
  }

  .success {
    width: 150rpx;
    height: 56rpx;
    font-size: 24rpx;
    background-color: #017EFE;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0px 5px 10px 0px rgba(1, 126, 254, 0.2);
    border-radius: 28px;
    color: #FFFFFF;

    .sureIcon {
      margin-right: 15rpx;
      width: 24rpx;
      height: 24rpx;
    }
  }

}

.pb30 {
  padding-bottom: 30rpx;
}

.f24 {
  font-size: 24rpx;
}

</style>
